package com.bfsuol.bfsuolframework.core.controller;

import com.bfsuol.bfsuolframework.core.BfsuolConstants;
import com.bfsuol.bfsuolframework.core.CoustomDir;
import com.bfsuol.bfsuolframework.core.utils.StringUtils;
import com.bfsuol.bfsuolframework.security.SecurityContext;
import com.bfsuol.bfsuolframework.security.entity.dto.Function;
import org.apache.log4j.Logger;
import org.assertj.core.util.Lists;
import org.assertj.core.util.Sets;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;


public class SpringControllerSupport  implements SpringController {
protected final Logger logger = Logger.getLogger(getClass());
	
	private String basePath = "";
	
	public SpringControllerSupport(){
		RequestMapping annotation = getClass().getAnnotation(RequestMapping.class);
		if(annotation != null && annotation.value() != null && annotation.value().length > 0){
			this.basePath = "/view"+annotation.value()[0];
		}
	}
	
	protected String getViewPath(String path){
		if(path.indexOf("/login/login") != -1){
			StringBuilder builder = new StringBuilder("");
			String url = getRequest().getRequestURL().toString().replace(":", "");
			CoustomDir coustomDir = CoustomDir.getInstance();
			List<String> cou = coustomDir.getCustomDirectory();
			if(!cou.isEmpty()){
				for(String d : cou){
					String ele[] = d.split("_");
					if(url.indexOf(ele[0]) != -1){
							return builder.append("custom/"+d+"/common/login").toString();
					}
				}
			}
			return "/common/login/login";
		}else{
			return basePath + (path.startsWith("/")?"":"/") + path;
		}
	}
	
	protected String getViewNamedPath(String path){
 		StringBuilder builder = new StringBuilder("");
 		String url = getRequest().getRequestURL().toString().replace(":", "");
		CoustomDir coustomDir = CoustomDir.getInstance();
		List<String> cou = coustomDir.getCustomDirectory();
		if(cou.isEmpty()){
			builder.append(basePath).append("/");
		}else{
			boolean flag = true;
			for(String d : cou){
				String ele[] = d.split("_");
				if(url.indexOf(ele[0]) != -1){
					if(ele[1].equals("deep")){
						builder.append("custom/"+d+basePath).append("/");
						flag = false;
						break;
					}
				}
			}
			if(flag){
				builder.append(basePath).append("/");
			}
		}
		
		String className = getClass().getSimpleName();
		if(className.endsWith("Controller") && className.length() > 10){
			className = className.substring(0, className.length() - 10);
		}
		builder.append(StringUtils.toUnderScoreCase(className,"-")).append("-");
		if(path.startsWith("/")){
			builder.append(path.substring(1));
		}else{
			builder.append(path);
		}
		return builder.toString();
	}
	
	/**
	 * 获得view路径排除projectCode
	 * @param path
	 * @return
	 */
	protected String getViewNamedPathExcludePcode(String path){
		
		StringBuilder builder = new StringBuilder("");
 		String url = getRequest().getRequestURL().toString().replace(":", "");
		CoustomDir coustomDir = CoustomDir.getInstance();
		List<String> cou = coustomDir.getCustomDirectory();
		
		String excludePcodeBasePath = this.excludePcodeFromUrl(basePath);
		
		if(cou.isEmpty()){
			builder.append(excludePcodeBasePath).append("/");
		}else{
			boolean flag = true;
			for(String d : cou){
				String ele[] = d.split("_");
				if(url.indexOf(ele[0]) != -1){
					if(ele[1].equals("deep")){
						builder.append("custom/"+d+excludePcodeBasePath).append("/");
						flag = false;
						break;
					}
				}
			}
			if(flag){
				builder.append(excludePcodeBasePath).append("/");
			}
		}
		
		String className = getClass().getSimpleName();
		if(className.endsWith("Controller") && className.length() > 10){
			className = className.substring(0, className.length() - 10);
		}
		builder.append(StringUtils.toUnderScoreCase(className,"-")).append("-");
		if(path.startsWith("/")){
			builder.append(path.substring(1));
		}else{
			builder.append(path);
		}
		return builder.toString();
	}
	
	
	public LoginInfo getLoginInfo() {
			return (LoginInfo)getRequest().getSession().getAttribute(BfsuolConstants.SESSION_LOGININFO_KEY);
	}

	public HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		return request;
	}
	
	public String getProjectCode()
	{
		LoginInfo li = (LoginInfo)getRequest().getSession().getAttribute(BfsuolConstants.SESSION_LOGININFO_KEY);
		String projectCode = (String)li.getParameter("projectCode");
		if(null == projectCode)
		{
			return null;
		}else
		{
			return projectCode;
		}
	}
	
	/**
	 * url中排除ProjectCode
	 * @param url
	 * @return
	 */
	private String excludePcodeFromUrl(String path) {
		
		if(path.startsWith("/"))
		{
			path = path.replaceFirst("/", "");
		}
		
		int firstFit = path.indexOf("/");
		String _url = path.substring(firstFit);
		
		return _url;
	}

	public List<Function> getRoleFunctions(){
		LoginInfo loginInfo = (LoginInfo) getRequest().getSession().getAttribute(BfsuolConstants.SESSION_LOGININFO_KEY);
		List<Function> functionList = new ArrayList<>();
		Set<Function> functions = SecurityContext.getRolesFunction(loginInfo.getRoleCodes());
		functionList.addAll(Optional.ofNullable(functions).orElse(Sets.newHashSet()));
		return functionList;
	}
}
